﻿package kaze.process.process 
{
    import ninjas.ninpo.process.states.OpenState;
    import ninjas.ninpo.vo.StateVO;
    
    import system.data.ValueObject;
    import system.process.Action;
    import system.process.Task;
    
    import vegas.models.maps.InitMapModelObject;
    import vegas.models.maps.MapModelObject;
    
    /**
     * Open the current state display in the state model.
     */
    public class OpenActualState extends Task 
    {
        /**
         * Creates a new OpenActualState instance.
         * @param model The state model reference.
         * @param init An optional action to initialize the state.
         */
        public function OpenActualState( model:MapModelObject = null , init:InitMapModelObject = null )
        {
            this.model = model ;
            this.init  = init  ;
        }
        
        /**
         * An optional action to initialize the state.
         */
        public var init:InitMapModelObject ;
        
        /**
         * The state model reference.
         */
        public var model:MapModelObject ;
        
        /**
         * Run the process.
         */
        public override function run( ...arguments:Array ):void 
        {
            notifyStarted() ;
            if ( init )
            {
                var menu:MapModelObject = init.model ;
                if ( menu == null )
                {
                    logger.warn(this + " failed, the menu model reference not must be null.") ; 
                    return ;
                }
                var first:* = init.first  ;
                if ( first )
                {
                    if ( first is ValueObject )
                    {
                        menu.setCurrentVO( first ) ;
                    }
                    else if ( menu.containsByID( first ) )
                    {
                        menu.setCurrentVO( menu.getVO( first )  ) ;
                    }
                }
                else
                {
                    logger.warn(this + " failed, the first value is null.") ; 
                }
            }
            else if ( model )
            {
                var current:StateVO = model.getCurrentVO() as StateVO ;
                if ( current )
                {
                    var open:OpenState = new OpenState( current ) ;
                    open.finishIt.connect( finish , 0 , true ) ; 
                    open.run() ;
                    return ;
                }
                else
                {
                    logger.warn(this + " failed, the state model isnt selected with a current StateVO reference.") ;
                }
            }
            init = null ; // destroy the init reference
            notifyFinished() ;
        }
        
        /**
         * Invoked when an Action finish this process.
         */
        protected function finish( action:Action = null ):void
        {
            notifyFinished() ;
        }
    }
}
